package net.dgg.zz.common.service;

import net.dgg.iboss.base.service.CmsService;
import net.dgg.iboss.base.service.OrfApiService;
import net.dgg.tmd.foundation.platform.org.service.OrganizationManager;
import net.dgg.tmd.foundation.platform.role.service.RoleService;
import net.dgg.tmd.foundation.platform.treebook.entity.TreeBook;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.zz.common.base.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by admin on 2018/4/28.
 */
@Service
public class CommonMangerExtService extends BaseService {
    @Resource
    private RoleService roleService;

    @Resource
    private CmsService cmsService;

    @Resource
    private OrganizationManager organizationManager;

    @Autowired
    private OrfApiService orfApiService;


    /**
     * 根据分类编码查询下级
     *
     * @param code  code
     * @param type  1：根据分类编码查询下级第一级分类（用于Select选择）
     *              2：根据分类编码查询所有下级分类（用于Tree选择无父级的）
     *              3：根据分类编码查询所有下级分类包含自己（用于Tree选择有父级的）
     *              4：根据分类编码查询所有下级分类（用于Tree选择无父级的）,查询包含禁用的字典
     * @param level 查询深度级数
     * @return
     */
    public List<TreeBook> queryTreeBookListByCode(String code, Integer type, Integer level) {
        //TODO
        List<TreeBook> list = new ArrayList<>();
        List<Map> datas = cmsService.getTreeBookList(code, 1, type, level);
        if (null != datas) {
            for (Map data : datas) {
                TreeBook book = new TreeBook();
                book.setId(Long.valueOf(data.get("id").toString()));
                book.setPid(Long.valueOf(data.get("pid").toString()));
                book.setCode(data.get("code") == null ? "" : data.get("code").toString());
                book.setName(data.get("name") == null ? "" : data.get("name").toString());
                book.setPcode(data.get("pcode") == null ? "" : data.get("pcode").toString());
                book.setDescription(data.get("description") == null ? "" : data.get("description").toString());
                list.add(book);
            }
        }
        return list;
    }

    public String selectBillNumberByCode(String code) {
        return cmsService.getBillNumber(code);
    }

    /**
     * @Title:
     * @Description: TODO 字典编码单个翻译
     * @param:
     * @return:
     * @throw:
     * @author: 代杨
     * @creat_date: 2018/6/22
     **/
    public Map getTreeBookObj(String code) {
        Map reMap = cmsService.getTreeBookObj(code);
        return reMap;
    }

    /**
     * 判断用户是否拥有角色
     *
     * @return
     */
    public boolean hasRole(UserEntity user, String code) {
        //TODO
        return code.equals("WL");
    }

    /**
     * 验证当前登录用户是否拥有某一个操作权限
     *
     * @param powerCode
     * @return
     */
    public boolean hasPower(String powerCode) {
        return roleService.exitsOperate4User(powerCode);
    }

    /**
     * 通过父级部门的id，获取本级及下级所有部门的id集合
     *
     * @param orgId
     * @return
     */
    public List<Long> getChildOrganizationList(Long orgId) {
        List<Long> orgs = new ArrayList<>();
        orgs.add(orgId);
        orgs.addAll(organizationManager.findOrgIdByAncestorId(orgId));
        return orgs;
    }


    /**
     * 根据父级code查询到父级和子集的code集合
     *
     * @param pcode
     * @return
     */
    public List<String> queryTreeBookCodesByParentCode(String pcode) {
        List<Map> datas = cmsService.getTreeBookList(pcode, null, null, null);
        if (null != datas) {
            List<String> codes = new ArrayList<>(datas.size());
            for (Map data : datas) {
                codes.add(data.get("code").toString());
            }
            return codes;
        }

        return null;
    }

    /**
     * 查询部门下面某角色的用户列表
     *
     * @param orgId  部门ID
     * @param locked 帐号状态
     * @param roleId 角色ID
     * @return
     */
    public List<Map> searchUser(Long orgId, Integer locked, Long roleId) {
        Map param = new HashMap();
        param.put("orgId", orgId);
        param.put("locked", locked);
        param.put("roleId", roleId);
        return cmsService.findUsers(param);
    }

    /**
     * 分页查询用户列表
     *
     * @param param
     * @return
     */
    public List<Map> searchUserPage(Map param) {
        try {
            Map result = cmsService.findPageUsers(param);
            if (result.isEmpty()) {
                param.put("count", 0);
                return new ArrayList<>(0);
            }
            param.put("count", result.get("recordsTotal"));
            return (List<Map>) result.get("data");
        } catch (Exception e) {
            param.put("count", 0);
            return new ArrayList<>(0);
        }
    }

    /**
     * @Title:
     * @Description: TODO 通过Map查询用户
     * @param: orgId部门  locked状态  roleId角色ID
     * @return:
     * @throw:
     * @author: 代杨
     * @creat_date: 2018/5/17
     **/
    public List<Map> searchUserByMap(Map param) {
        return cmsService.findUsers(param);
    }

    /**
     * @Title:
     * @Description: TODO 通过id查询用户
     * @param:
     * @return:
     * @throw:
     * @author: 代杨
     * @creat_date: 2018/5/17
     **/
    public Map searchUserById(Long id) {
        return cmsService.findUser(id);
    }

//    /**
//     * 根据工号查找用户
//     *
//     * @param userLoginName 工号
//     * @return
//     */
//    public Map findUserByLoginName(String userLoginName) {
//        Map para = new HashMap();
//        para.put("loginName", userLoginName);
//        List<Map> users = cmsService.findUsers(para);
//        Assert.isTrue(users != null && users.size() == 1, "未能根据工号：" + userLoginName + "找到唯一用户。");
//        return users.get(0);
//    }


    /**
     * @Title:
     * @Description: TODO 查询部门列表接口
     * @param:
     * @return:
     * @throw:
     * @author: 代杨
     * @creat_date: 2018/5/11
     **/
    public List<Map> findOrgs(Map params) {
        List<Map> list = cmsService.findOrgs(params,1);
        return list;
    }

    /**
     * @Title:
     * @Description: TODO 查询部门列表接口，获取传入部门及子部门的id集合字符串，以逗号分割
     * @param:
     * @return:
     * @throw:
     * @author:黄文娟
     * @creat_date: 2018/5/28 10:12
     **/
    public String[] findOrgsToArray(Long orgId) {
        Map orgmap = new HashMap();
        Assert.isTrue(orgId != null, "请传入部门id");
        orgmap.put("orgId", orgId);
        List<Map> orgList = cmsService.findOrgs(orgmap,1);
        if (null != orgList && !orgList.isEmpty()) {
            String[] ids = new String[orgList.size()];
            for (int i = 0; i < orgList.size(); i++) {
                ids[i] = (orgList.get(i)).get("id") + "";
            }
            return ids;

        }
        return null;
    }

    /**
     * @Title:
     * @Description: TODO 查询部门接口
     * @param:
     * @return:
     * @throw:
     * @author: 代杨
     * @creat_date: 2018/5/11
     **/
    public Map findOrg(Long id) {
        Map map = cmsService.findOrg(id);
        return map;
    }

    /**
     * @Title:
     * @Description: TODO 查询当前部门的事业部
     * @param:
     * @return:
     * @throw:
     * @author: 代杨
     * @creat_date: 2018/5/11
     **/
    public Map findBusDeptById(Long deptId) {
        Map map = cmsService.findOrgParent(deptId, "ORG_LEVEL_1");
        return map;
    }

    /**
     * @Title:
     * @Description: TODO 查询当前部门的分公司
     * @param:
     * @return:
     * @throw:
     * @author: 代杨
     * @creat_date: 2018/5/28
     **/
    public Map findCompanyById(Long deptId) {
        Map map = cmsService.findOrgParent(deptId, "ORG_LEVEL_0");
        return map;
    }

    /**
     * @Title:
     * @Description: TODO 查询当前业态下的产品和商品
     * @param:
     * @return:
     * @throw:
     * @author:黄文娟
     * @creat_date: 2018/5/23 15:18
     **/
    public List<Map> queryProduct(Map params) {
        List<Map> map = cmsService.findProduct(params);
        return map;
    }

    public Map queryGoods(Map params) {
        Map map = cmsService.productInfo(params);
        return map;
    }

    /**
     * 根据工号获取iboss的user 实体
     *
     * @param userLoginName
     */
    public Map getUserByLoginName(String userLoginName) {
        //获取用户
        List<Map> userEntitys = this.searchUserByMap(new HashMap() {{
            put("loginName", userLoginName);
        }});
        return userEntitys.size() > 0 ? userEntitys.get(0) : null;
    }

}
